package com.ja.openchat.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.gson.JsonObject;
import com.ja.openchat.ui.chat.MessageReactionUserDialog;
import com.ja.openchat.ui.message.adapter.MessageReactionAdapter;
import com.lxj.xpopup.XPopup;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageReaction;
import com.zy.openchat.core.model.message.UiMessage;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MessageReactionView extends RecyclerView implements TgResultBlock<List<MessageReaction>>, OnItemClickListener {

    public MessageReactionView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public MessageReactionView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MessageReactionView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        setVisibility(View.GONE);
    }


    public void setMessage(UiMessage message){
        setTag(message);
        if(message.isRequestMessageReactions){
            if(Common.isEmpty(message.reactions)){
                setVisibility(View.GONE);
            }else{
                Adapter adapter = getAdapter();
                if(adapter==null){
                    setLayoutManager(new FlexboxLayoutManager(getContext()));
                    adapter = new MessageReactionAdapter(message.reactions);
                    setAdapter(adapter);
                }else if(adapter instanceof BaseQuickAdapter&&((BaseQuickAdapter) adapter).getData() == message.reactions){
                    adapter.notifyDataSetChanged();
                }else if(adapter instanceof BaseQuickAdapter){
                    ((BaseQuickAdapter) adapter).setNewInstance(message.reactions);
                }
                if(adapter instanceof BaseQuickAdapter){
                    ((BaseQuickAdapter) adapter).setOnItemClickListener(this);
                }
                setVisibility(View.VISIBLE);
            }
        }else{
            ChatInfo chatInfo = TelegramManager.getTelegramManager().getTgData().chatInfo(message.message.chat_id);
            if(chatInfo == null){
                return;
            }
            TelegramManager.getTelegramManager().getMessagesReaction(getContext(),message.message.chat_id,chatInfo.isGroup()?2:1,message.message.id,this);
            setVisibility(View.GONE);
        }
    }



    private boolean isDoubleClick(View view){
        long current = System.currentTimeMillis();
        if(view.getTag() instanceof Long){
            long preClickTime = (Long) view.getTag();
            view.setTag(current);
            if((current - preClickTime)>800){
                return false;
            }else{
                return true;
            }
        }else{
            view.setTag(current);
            return false;
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if(!isDoubleClick(view)){
            if(getTag()!=null&&getTag() instanceof UiMessage) {
                UiMessage message = (UiMessage) getTag();
                showList(message.reactions);
            }
            return;
        }
        Object object = adapter.getItem(position);
        if(object!=null&&object instanceof MessageReaction){
            MessageReaction messageReaction = (MessageReaction) object;
            if(getTag()!=null&&getTag() instanceof UiMessage){
                UiMessage message = (UiMessage) getTag();
                if(UserInfo.getUserInfo()!=null){
                    MessageReaction premessageReaction = message.haveReactionByCurrentUserId();
                    if(premessageReaction!=null&&premessageReaction.reactionId == messageReaction.reactionId){
                        EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_Td_Chat_Send_Reaction,message,0));
                    }else{
                        EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_Td_Chat_Send_Reaction,message,messageReaction.reactionId));
                    }
                }
            }
        }
    }

    private void showList(List<MessageReaction> messageReactions){
        if(Common.isEmpty(messageReactions)){
            return;
        }
        List<MessageReaction> total = new ArrayList<>();
        for(MessageReaction reaction:messageReactions){
            if(!Common.isEmpty(reaction.userIds)){
                for(Long userId:reaction.userIds){
                    total.add(new MessageReaction(userId,reaction.reactionId));
                }
            }
        }
        new XPopup.Builder(getContext())
                .isDestroyOnDismiss(true)
                .asCustom(new MessageReactionUserDialog(getContext(),total))
                .show();
    }

    @Override
    public void onResult(Map<String, Object> request, JsonObject response, List<MessageReaction> obj) {
        if(getTag()!=null&&getTag() instanceof UiMessage){
            UiMessage message = (UiMessage) getTag();
            message.isRequestMessageReactions = true;
            message.reactions = obj;
            setMessage(message);
        }
    }

    @Override
    public void onTimeout(Map<String, Object> request) {

    }
}
